<?php
namespace frontend\modules\Api\controllers;

use common\event\TallyEvent;
use common\models\TallyArap;
use common\models\TallyCategory;
use common\models\TallyRecord;
use common\services\TallyArapService;
use common\services\TallyPmService;
use common\services\TallyRecordService;
use common\services\TallyService;
use common\services\ToolService;
use Yii;
use yii\db\Exception;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

/**
 * 应收应付管理
 * Class TallyArapController
 *
 * @package frontend\modules\Api\controllers
 */
class TallyArapController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 重载初始化方案
     */
    public function init()
    {
        parent::init();
        // 注册监听事件
        $this->on(TallyEvent::RECORD_LOG_EVENT,['common\models\Tally','recordLog']);
    }

    /**
     * 获取应收应付款项列表
     * @throws
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        // 默认取出所有状态
        $list = TallyArapService::getList($condition,$uid);
        $retData['data'] = [];
        $retData['pageInfo'] = [];
        // 遍历拼装附件数据
        foreach ($list['data'] as $lv) {
            $tmpData = $lv->toArray();
            $tmpData['attachment']  = $lv->attachment;
            $tmpData['type_txt']    = '挂账';
            $tmpData['is_gua']    = 1;
            $tmpData['state_txt']  = TallyArap::getStatusTxt($lv['state']);
            $monthAmount = TallyRecordService::getSumAmount($condition,$lv->id);
            $tmpData['now_price'] = bcsub($monthAmount,0,2);
            $tmpData['all_price'] = bcsub($lv->amount,$lv->amount_remain,2);
            $retData['data'][] = $tmpData;
        }
        $retData['pageInfo'] = $list['pageInfo'];
        return self::successResponse($retData);
    }

    /**
     * 核销记录明细
     * @throws \yii\base\ExitException
     */
    public function actionDetails() {
        $id = Yii::$app->getRequest()->get('id');
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        if(!$id){
            return self::failureResponse(500,'挂账Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $list = TallyArapService::getRecordList($id);
        // 遍历拼装附件数据
        $retData = [];
        foreach ($list as $lv) {
            $tmpData = $lv->toArray();
            $tmpData['attachment']  = $lv->attachment;
            $tmpData['type_txt']    = '挂账';
            $tmpData['state_txt']  = TallyRecord::getStatusTxt($lv['state']);
            $retData[] = $tmpData;
        }
        return self::successResponse($retData);
    }

    /**
     *  账单审核
     * @throws \yii\base\ExitException
     * @desc
     */
    public function actionAudit()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'挂账Id不能为空');
        }
        $memo = Yii::$app->getRequest()->post('memo','');
        $state = Yii::$app->getRequest()->post('state');
        if(!in_array($state,[TallyArap::STATE_REFUSED,TallyArap::STATE_VALID])){
            return self::failureResponse(500,'状态参数校验失败');
        }
        // 获取账单数据
        $tallyRecord = TallyArap::find()->where([
            'id' => $id,
        ])->one();
        if(!$tallyRecord) {
            return self::failureResponse(500,'挂账数据不存在');
        }
        // 用户与账本权限角色关系
        $this->checkRolePermission($this->_user['id'],$tallyRecord->tally_id,'audit');
        // 更新账单状态
        $tallyRecord->state =$state;
        $result = $tallyRecord->save();
        if(!$result) {
            return self::failureResponse(500,'状态更新失败.');
        }else{
            // 触发账单记录事件
            $this->triggerEvents([
                'tally_id' => $tallyRecord->tally_id,
                'uid'   => $this->_user['id'],
                'type'  => 2,
                'content' => '审核挂账账单,id:'.$id.',意见:'.TallyArap::getStatusTxt($state).',备注:'.$memo,
            ]);
            return self::successResponse();
        }
    }

    /**
     * 删除应收应付记录
     * @throws
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'记录Id不能为空');
        }
        $result = TallyArapService::delete([
            'id'    => $id,
            'uid'   => $this->_user['id']
        ]);
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyArapService::getError());
        }
    }

    /**
     * 某一时间段应付内债务统计 这是总计 总的应收付数据
     * @throws \yii\base\ExitException
     */
    public function actionCount()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        if(Yii::$app->request->isPost){
            $tallyId = Yii::$app->getRequest()->post('tally_id');
        }else{
            $tallyId = Yii::$app->getRequest()->get('tally_id');
        }
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        $retData  = TallyArapService::countArap($condition,$uid);
        return self::successResponse($retData);
    }

    /**
     * 一段时间内的应收付统计，包括以下数据：
     * 1、该时间段新增加的应收付记录：应收额、应付额 通过查询arap表获得
     * 2、该时间段内核销的应收付记录：已收额、已付额 通过查询record表获得
     * @throws \yii\base\ExitException
     */
    public function actionCountPeriod()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        $retData  = TallyArapService::countArapPeriod($condition,$uid);
        return self::successResponse($retData);
    }

    /**
     * 应收付记录导出（只是统计 不包括核销记录）
     * @throws \yii\base\ExitException
     */
    public function actionExport()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $tallyInfo = TallyService::getOne($tallyId);
        if(!$tallyInfo){
            return self::failureResponse(500,'账本信息不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        // 默认取出所有状态 修改返回为data的bug
        $list = TallyArapService::getAll($condition);
        // 遍历拼装附件数据
        $retData = [] ;
        foreach ($list as $lv) {
            $accountStr = $lv['account_name'];
            $tmpData = [
                substr($lv['tally_time'],0,10),//账单时间
                TallyRecord::getTypeTxt($lv['type']),
                $lv['category_pname'],
                $lv['category_name'],
                $accountStr,
                $lv['amount'],
                ToolService::groupMathAdd([
                    $lv['amount'],
                    -1*$lv['amount_remain'],
                ]),
                $lv['amount_remain'],
                ltrim($lv['project_name'].'-'.$lv['store_name'],'-'),
                $lv['member_name'],
                $lv['memo'],
                TallyArap::getStatusTxt($lv['state']),
                $lv['created_time'], //录入时间
            ];
            $retData[] = $tmpData;
        }
        $filename = $tallyInfo['title'].'_应收付_'.date('Ymd').'-'.rand(1000,9999).'.csv';
        ToolService::downLoadCsv($filename,[
            '账单日期',
            '类别',
            '一级分类',
            '二级分类',
            '账户',
            '总金额',
            '已核销金额',
            '待核销金额',
            '客户/供应商',
            '员工',
            '备注',
            '状态',
            '录入时间',
        ],$retData);
        $filepath = Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
        return self::successResponse(['filepath'=>$filepath]);
    }
}
